﻿#ifndef __GNUC__
#pragma execution_character_set("utf-8")
#endif

#include "test_{ $Project }XML.h"
#include "../{ $Project }XML/{ $Project }XML.h"

#include <QFile>
#include <QFileDialog>

using namespace ns{ $Project }XML;

test_{ $Project }XML::test_{ $Project }XML(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
}

void test_{ $Project }XML::on_actionNew_triggered()
{
	ui.treeWidget->clear();
}

//在pItem结点下插入属性
void InsertProperties(QTreeWidgetItem *pItem, const QStringList &propList)
{
	QStringList qlist;

	qlist << QStringLiteral("属性");
	QTreeWidgetItem *pPropItem = new QTreeWidgetItem(qlist);
	pItem->addChild(pPropItem);
	for (auto &prop : propList)
	{
		qlist.clear();
		qlist << prop;
		QTreeWidgetItem *pSubItem = new QTreeWidgetItem(qlist);
		pPropItem->addChild(pSubItem);
	}
}

//在pItem结点下递归插入属性子和结点
void InsertSubItems(QTreeWidgetItem *pItem, const QString &subNode)
{
	QStringList qlist;
	qlist << subNode;
	QTreeWidgetItem *pSubItem = new QTreeWidgetItem(qlist);
	pItem->addChild(pSubItem);
}

void test_{ $Project }XML::on_actionOpen_triggered()
{
	//输入文件名
	m_sXMLPath = QFileDialog::getOpenFileName(this, "打开文件", "", tr("XML文件 (*.xml *.XML);;所有文件 (*.*)"));
	if (m_sXMLPath.isEmpty())
	{
		on_actionNew_triggered();
		return;
	}

	QFile file(m_sXMLPath);
	if (!file.open(QFile::ReadOnly | QFile::Text))
		return;
	QString contents = file.readAll();
	ui.textEdit->setPlainText(contents);
	file.close();

	//读入XML文件
	C{ $Project }XML doc;
	doc.LoadFromFile(m_sXMLPath.toStdWString());
	//doc.SaveToFile(someFile, true);

	//将XML显示在树状窗口
	ui.treeWidget->clear();
	QTreeWidgetItem *pItem = ui.treeWidget->invisibleRootItem();
	for (auto &_node : doc.{ $Project })
	{
		QStringList qlist;
		qlist << _node._nodeName_;
		QTreeWidgetItem *pSubItem = new QTreeWidgetItem(qlist);
		pItem->addChild(pSubItem);

		InsertProperties(pSubItem, _node.propList);

		for (auto &_subnode : _node.subNodes)
		{
			InsertSubItems(pSubItem, _subnode);
		}
	}

}

void test_{ $Project }XML::on_actionSave_triggered()
{
	if (m_sXMLPath.isEmpty()) return;

	QFile file(m_sXMLPath);
	if (!file.open(QFile::WriteOnly | QFile::Text))
		return;

	//file.write(m_sOldContent.toStdString().c_str());
	file.close();
}

void test_{ $Project }XML::on_actionSaveAs_triggered()
{
	QString sFile = QFileDialog::getSaveFileName(this, tr("另存为"), m_sXMLPath, tr("XML文件 (*.xml *.XML);;所有文件 (*.*)"));
	if (sFile.isEmpty()) return;
	m_sXMLPath = sFile;
	on_actionSave_triggered();
}
